package com.healthmgmt.common.service.impl;

import com.healthmgmt.common.config.AliyunSmsConfig;
import com.healthmgmt.common.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("smsService")
@ConditionalOnProperty(name = "cloud.sms.type", havingValue = "aliyun")
public class AliyunSmsServiceImpl implements SmsService {

    @Autowired
    private AliyunSmsConfig config;

    @Override
    public boolean sendSms(String phone, Map<String, String> params) {
        try {
            // 1. 创建配置
            com.aliyun.teaopenapi.models.Config clientConfig = new com.aliyun.teaopenapi.models.Config()
                    .setAccessKeyId(config.getAliyun().getAccessKeyId())
                    .setAccessKeySecret(config.getAliyun().getAccessKeySecret());

            // 2. 设置服务端点（不同区域需调整）
            clientConfig.endpoint = "dysmsapi.aliyuncs.com";

            // 3. 创建客户端
            com.aliyun.dysmsapi20170525.Client client =
                    new com.aliyun.dysmsapi20170525.Client(clientConfig);

            // 4. 构建请求对象
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendReq =
                    new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                            .setPhoneNumbers(phone)
                            .setSignName(config.getAliyun().getSignName()) // 短信签名
                            .setTemplateCode(config.getAliyun().getTemplateCode())
                            .setTemplateParam(com.aliyun.teautil.Common.toJSONString(params));

            // 5. 发送请求并获取响应
            com.aliyun.dysmsapi20170525.models.SendSmsResponse response =
                    client.sendSms(sendReq);

            // 6. 检查响应状态（"OK"表示成功）
            return "OK".equalsIgnoreCase(response.getBody().getCode());

        } catch (Exception e) {
            throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
        }
    }
}
